/*
 * Copyright@www.it1997.com.
 * @Author: 陈晓晨
 * @Date: 2020/6/3
 * Description:版权所有 QQ:376231445
 */

package com.it1997.it1997admin.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException accessDeniedExcepton) throws IOException, ServletException {
        //1. 判断用户是否是ajax请求
        boolean isAjax=ControllerTools.isAjaxRequest(httpServletRequest);
        //2.判断响应是否提交
        if(!httpServletResponse.isCommitted()){     //响应没有提交
            if(isAjax){     //请求是ajax请求
                String msg=accessDeniedExcepton.getMessage();
                log.info("accessDeniedException.message:"+msg);
                String accessDeniedMsg="{\"code\":\"403\",\"msg\":\"没有权限\"}";
                ControllerTools.print(httpServletResponse,accessDeniedMsg);
            }else {     //不是ajax请求
                httpServletRequest.setAttribute(WebAttributes.ACCESS_DENIED_403,accessDeniedExcepton);
                httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
                RequestDispatcher requestDispatcher=httpServletRequest.getRequestDispatcher("/403");
                requestDispatcher.forward(httpServletRequest,httpServletResponse);
            }
        }
    }
    /*
    * 静态内部类
    * 请求转换工具
    * */
    public static class ControllerTools {
        public static boolean isAjaxRequest(HttpServletRequest request) {
            return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        }

        public static void print(HttpServletResponse response, String msg) throws IOException {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(msg);
            writer.flush();
            writer.close();
        }
    }
}
